<template>
  <!-- 2. 准备具备宽高的容器 -->
  <div class="chart" ref="chartRef"></div>
</template>

<script lang="ts" setup>
// 1. 引入echarts
import * as echarts from "echarts";
import { onMounted, ref } from "vue";

// 找不到。原因：因为当前在setup中，setup相当于beforeCreate和created，此时页面还未渲染，拿不到DOM元素
// const myEcharts = echarts.init(document.querySelector(".chart"));

const chartRef = ref();

onMounted(() => {
  // 3. 初始化echarts实例
  // document.querySelector获取DOM元素不太合适，应该用ref
  // const myEcharts = echarts.init(document.querySelector(".chart"));
  const myEcharts = echarts.init(chartRef.value);
  // 4. 准备图表配置项：option
  const option = {
    // 标题组件
    title: {
      text: "各行业程序员数量",
      textStyle: {
        color: "#fff",
        fontSize: "12px",
      },
      left: "center",
      top: 10,
    },
    // x轴组件
    xAxis: {
      data: [
        "旅游行业",
        "游戏行业",
        "电商行业",
        "医疗行业",
        "金融行业",
        "教育行业",
        "餐饮行业",
      ],
      // 刻度线的文字
      axisLabel: {
        color: "rgba(255, 255, 255, 0.6)",
        fontSize: 8,
      },
      // 刻度线
      axisTick: {
        show: false,
      },
      // 坐标轴线
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(255, 255, 255, .1)",
        },
      },
    },
    // y轴组件
    yAxis: {
      // 刻度线的文字
      axisLabel: {
        color: "rgba(255, 255, 255, 0.6)",
        fontSize: 8,
      },
      // 刻度线
      axisTick: {
        show: false,
      },
      // 坐标轴线
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(255, 255, 255, .1)",
        },
      },
      splitLine: {
        lineStyle: {
          color: "rgba(255, 255, 255, .1)",
        },
      },
    },
    // 系列组件：设置图表类型、数据、样式等
    series: {
      type: "bar",
      data: [300, 200, 400, 250, 550, 450, 350],
      barWidth: 15,
      itemStyle: {
        borderRadius: 2,
      },
    },
    // 提示框组件
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0, 0, 0, .5)",
      borderWidth: 0,
      textStyle: {
        color: "#fff",
        fontSize: 12,
      },
      formatter: `{b}: {c}`,
    },
    // 图例组件：切换图标显示隐藏
    // legend: {},
    // 布局组件：设置图表在容器中大小
    grid: {
      top: 40,
      bottom: 10,
      left: 10,
      right: 10,
      containLabel: true,
    },
  };
  // 5. 调用setOption方法来渲染图表
  myEcharts.setOption(option);
});

defineOptions({
  name: "BarChart",
});
</script>

<style scoped lang="scss">
.chart {
  // width: 100%;
  height: 100%;
}
</style>
